<template>
	<el-drawer
	  v-model="dialog.visible"
	  :title="dialog.title"
	  append-to-body
	  @close="closeDialog"
	  :close-on-click-modal="false"
	  size="750"
	>
		<el-steps :active="active"  align-center finish-status="success">
			<el-step title="Step 1" description="数据结构" />
			<el-step title="Step 2" description="清洗与规范" />
			<el-step title="Step 3" description="输出" />
			<el-step title="Step 4" description="触发" />
			<el-step title="Step 5" description="完成" />
		</el-steps>
		
		<div class="step-content">
			<div v-if="active==0">
				<el-form
					ref="contentFormRef"
					:model="contentFormData"
					:rules="contentFormRules"
					label-width="120px"
				>
					<div class="section-title">
					  <span class="title-form_primary">响应内容</span>
					</div>
					<el-form-item label="取值字段标识" prop="valueFieldIdentifier">
						<el-input v-model="contentFormData.valueFieldIdentifier" placeholder="请输入取值字段(层级提取请用英文.分隔,如:result.data)" />
					</el-form-item>
					
					<el-form-item label="取值字段类型" prop="valueFieldType">
						<Dict v-model="contentFormData.valueFieldType" code="field_type" style="width: 100%;" />
					</el-form-item>
					
					<el-form-item label="取值Json字段" prop="valueFieldJsonReturnType" v-if="contentFormData.valueFieldType=='map'">
						<el-radio-group v-model="contentFormData.valueFieldJsonReturnType">
							<el-radio label="Key字段" :value="'key'" />
							<el-radio label="Value字段"  :value="'value'"/>
							<el-radio label="All字段"  :value="'all'"/>
						</el-radio-group>
					</el-form-item>
					
				</el-form>
				
			</div>
			
			<div v-if="active==1">
				<div class="section-title">
				  <span class="title-form_primary">字段信息</span>
				  <div>
					  <el-button 
						type="primary" 
						link 
						@click="handleParseJson" 
					  >
						<el-icon><Document /></el-icon>解析JSON
					  </el-button>
					  
					  <el-button type="primary" link @click="handleAddField">
						<el-icon><Plus /></el-icon>添加字段
					  </el-button>
					  
				  </div>
				</div>
				
				<!-- JSON解析对话框 -->
				<el-dialog
					v-model="jsonDialog.visible"
					title="JSON解析"
					width="50%"
					append-to-body
					destroy-on-close
				>
					<el-form>
						<el-form-item>
							<MonacoEditor
								v-model="jsonDialog.content"
								language="json"
								:options="{ 
									theme: 'vs-dark',
									minimap: { enabled: false },
									lineNumbers: 'on',
									scrollBeyondLastLine: false,
									wordWrap: 'on',
									automaticLayout: true
								}"
								style="height: 300px"
							/>
						</el-form-item>
					</el-form>
					<template #footer>
						<el-button @click="jsonDialog.visible = false">取 消</el-button>
						<el-button type="primary" @click="parseJsonContent">解 析</el-button>
					</template>
				</el-dialog>
				
				<div class="param-model-content">
					<draggable
						v-model="fieldDefinitions"
						:animation="150"
						handle=".drag-handle"
						item-key="identifier"
						:component-data="{
						  tag: 'div',
						  type: 'transition-group',
						  name: !drag ? 'flip-list' : null
						}"
						@start="drag = true"
						@end="drag = false"
					>
						<template #item="{ element: row, index }">
							<div class="param-model-content-row">
								<el-button class="drag-handle" link>
									<el-icon><Rank /></el-icon>
								</el-button>
								<div class="param-info">
									<div class="param-name">
										{{ row.inputFieldName }}({{ row.inputFieldIdentifier }})
									</div>
									<div class="param-detail">
										<span>输出字段名: {{ row.outputFieldName }}</span>
										<span>输出字段标识: {{ row.outputFieldIdentifier }}</span>
										<el-tag :type="row.outputValueFromInput=='input' ? 'success' : 'info'" size="small">
											{{ row.outputValueFromInput =='input' ? '输入值' : '默认值' }}
										</el-tag>
									</div>
								</div>
								<div class="param-actions">
									<el-button type="primary" link @click="handleEditField(index,row)">
										<el-icon><Edit /></el-icon>编辑
									</el-button>
									<el-button type="danger" link @click="removeField(index)">
										<el-icon><Delete /></el-icon>删除
									</el-button>
								</div>
							</div>
						</template>
					</draggable>
					<div v-if="fieldDefinitions.length === 0" class="empty-tip">
						暂无字段，请点击上方按钮添加
					</div>
				</div>
			</div>
			
			<div v-if="active==2">
				
				<div class="section-title">
				  <span class="title-form_primary">输出信息</span>
				  <el-button type="primary" link @click="handleAddOutputTarget">
				    <el-icon><Plus /></el-icon>添加输出
				  </el-button>
				</div>
				
				<div class="param-model-content">
					<draggable
						v-model="outputDefinitions"
						:animation="150"
						handle=".drag-handle"
						item-key="identifier"
						:component-data="{
						  tag: 'div',
						  type: 'transition-group',
						  name: !drag ? 'flip-list' : null
						}"
						@start="drag = true"
						@end="drag = false"
					>
						<template #item="{ element: row, index }">
						  <div class="param-model-content-row">
							<el-button 
							  class="drag-handle" 
							  link
							>
							  <el-icon><Rank /></el-icon>
							</el-button>
							<div class="param-info">
							  <div class="param-name">{{ row.type }}</div>
							  <div class="param-detail">
								<span v-if="row.type=='OLTP'">表名: {{ row.table }}</span>
								<span v-if="row.type=='OLTP'">主键: {{ row.primarykey }}</span>
								<span v-if="row.type=='MQTT'">主题: {{ row.name }}</span>
								<span v-if="row.type=='MQTT'">QoS等级: {{ row.qos }}</span>
								<span v-if="row.type=='MQTT'">留存: {{ row.retained === '0' ? '否' : '是' }}</span> 
								
								<span v-if="row.type=='REDIS'">常量缓存:  {{ row.fixedRedisKey === '0' ? '否' : '是' }}</span>
								<span v-if="row.type=='REDIS' && row.fixedRedisKey=='0'">缓存取值字段:  {{ row.redisKeyValueField}}</span>
								<span v-if="row.type=='REDIS' && row.fixedRedisKey=='1'">常量缓存Key值:  {{ row.fixedRedisKeyValue}}</span>
								
								<el-tag :type="row.fieldStandardSame=='1' ? 'success' : 'info'" size="small">
								  {{ row.fieldStandardSame=='1' ? '一致' : '不一致' }}
								</el-tag>
							  </div>
							</div>
							<div class="param-actions">
							  <el-button type="primary" link @click="handleEditOutputTarget(index,row)">
								<el-icon><Edit /></el-icon>编辑
							  </el-button>
							  <el-button type="danger" link @click="removeOutputTarget(index)">
								<el-icon><Delete /></el-icon>删除
							  </el-button>
							</div>
						  </div>
						</template>
					</draggable>
					<div v-if="outputDefinitions.length === 0" class="empty-tip">
						暂无输出信息，请点击上方"添加输出"按钮添加
					</div>
				</div>
			</div>
			
			<div v-if="active==3">
				<el-form
					ref="triggerFormRef"
					:model="triggerFormData"
					:rules="triggerFormRules"
					label-width="120px"
				>
					
					<el-form-item label="触发器类型" prop="type" required>
						<el-select v-model="triggerFormData.type" >
							<el-option label="定时器" value="timer" />
							<el-option label="事件" value="event" />
						</el-select>
					</el-form-item>
					
					<el-form-item label="执行方式" prop="exec" v-if="triggerFormData.type=='timer'">
						<el-radio-group v-model="triggerFormData.exec" >
						  <el-radio value="interval">间隔</el-radio>
						  <el-radio value="cron">CRON</el-radio>
						  <el-radio value="fixedTime">固定时间点</el-radio>
						  <el-radio value="monthly">每月</el-radio>
						  <el-radio value="yearly">每年</el-radio>
						</el-radio-group>
					</el-form-item>
					
					<!-- 间隔执行配置 -->
					<template v-if="triggerFormData.type=='timer' && triggerFormData.exec=='interval'">
						<el-form-item label="间隔时间" prop="interval" required>
							<el-input-number v-model="triggerFormData.interval" :min="1" />
						</el-form-item>
						<el-form-item label="时间单位" prop="unit" required>
							<el-select v-model="triggerFormData.unit">
								<el-option label="秒" value="seconds" />
								<el-option label="分钟" value="minutes" />
								<el-option label="小时" value="hours" />
								<el-option label="天" value="days" />
							</el-select>
						</el-form-item>
					</template>

					<!-- CRON表达式配置 -->
					<el-form-item 
						label="CRON表达式" 
						prop="expression" 
						v-if="triggerFormData.type=='timer' && triggerFormData.exec=='cron'"
						required
					>
						<el-input v-model="triggerFormData.expression" placeholder="请输入CRON表达式">
							<template #append>
								<el-button @click="openCronBuilder">
									<el-icon><Tools /></el-icon>生成器
								</el-button>
							</template>
						</el-input>
						<template #extra>
							<div class="cron-tips">
								<p>格式: 秒 分 时 日 月 周</p>
								<p>示例: 0 0 12 * * ? (每天12点执行)</p>
								<p>常用表达式:</p>
								<el-tag 
									v-for="(cron, index) in commonCrons" 
									:key="index"
									class="cron-tag"
									@click="triggerFormData.expression = cron.value"
								>
									{{ cron.label }}
								</el-tag>
							</div>
						</template>
					</el-form-item>

					<!-- 固定时间点配置 -->
					<el-form-item 
						label="执行时间" 
						prop="time" 
						v-if="triggerFormData.type=='timer' && triggerFormData.exec=='fixedTime'"
						required
					>
						<el-time-picker v-model="triggerFormData.time" format="HH:mm:ss" />
					</el-form-item>
					
					<!-- 每月执行配置 -->
					<template v-if="triggerFormData.type=='timer' && triggerFormData.exec=='monthly'">
						<el-form-item label="每月几号" prop="dayOfMonth" required>
							<el-input-number v-model="triggerFormData.dayOfMonth" :min="1" :max="31" />
						</el-form-item>
						<el-form-item label="执行时间" prop="timeOfDay" required>
							<el-time-picker v-model="triggerFormData.timeOfDay" format="HH:mm:ss" />
						</el-form-item>
					</template>

					<!-- 每年执行配置 -->
					<template v-if="triggerFormData.type=='timer' && triggerFormData.exec=='yearly'">
						<el-form-item label="月份" prop="month" required>
							<el-input-number v-model="triggerFormData.month" :min="1" :max="12" />
						</el-form-item>
						<el-form-item label="日期" prop="dayOfMonth" required>
							<el-input-number v-model="triggerFormData.dayOfMonth" :min="1" :max="31" />
						</el-form-item>
						<el-form-item label="执行时间" prop="timeOfDay" required>
							<el-time-picker v-model="triggerFormData.timeOfDay" format="HH:mm:ss" />
						</el-form-item>
					</template>
				</el-form>
			</div>
			
			<div v-if="active==4">
				<el-form
					ref="completedFormRef"
					:model="completedFormData"
					:rules="completedFormRules"
					label-width="120px"
				>
				
					<el-form-item label="是否启用" prop="enabled" >
						<el-radio-group v-model="completedFormData.enabled" >
						  <el-radio value="0">禁用</el-radio>
						  <el-radio value="1">启用</el-radio>
						</el-radio-group>
					</el-form-item>
					
					<el-form-item label="默认执行" prop="defaultRunning" >
						<el-radio-group v-model="completedFormData.defaultRunning" >
						  <el-radio value="0">手动</el-radio>
						  <el-radio value="1">自动</el-radio>
						</el-radio-group>
					</el-form-item>
					
					<el-form-item label="备注" prop="remark" >
						<el-input v-model="completedFormData.remark" type="textarea" maxlength="250" placeholder="请输入备注信息" show-word-limit />
					</el-form-item>
				</el-form>
			</div>
		</div>
	
		<template #footer>
		  <div class="dialog-footer">
			<el-button type="primary" @click="preStep"  :loading="loading" v-if="active!=0  ||  !(isEdit==true && active==0 )">上一步</el-button>
			<el-button type="primary" @click="nextStep"  :loading="loading" v-if="active!=4">下一步</el-button>
			<el-button type="primary" @click="submitForm" v-if="active==4"  :loading="loading">确 定</el-button>
			<el-button @click="closeDialog" :loading="loading">取 消</el-button>
		  </div>
		</template>
		
		<EditFieldDrawer  ref="editFieldDrawerRef" @success="handleEditFieldSuccess"></EditFieldDrawer>
		<EditOutputTargetDrawer  ref="editOutputTargetDrawerRef" @success="handleEditOutputTargetSuccess"></EditOutputTargetDrawer>
		
		<!-- CRON表达式生成器对话框 -->
		<el-dialog
			v-model="cronDialog.visible"
			title="CRON表达式生成器"
			width="600px"
			append-to-body
			destroy-on-close
		>
			<el-form label-width="100px">
				<el-form-item label="执行类型">
					<el-radio-group v-model="cronDialog.type">
						<el-radio :value="'every'">每</el-radio>
						<el-radio :value="'specific'">指定</el-radio>
						<el-radio :value="'cycle'">周期</el-radio>
					</el-radio-group>
				</el-form-item>

				<!-- 每 -->
				<template v-if="cronDialog.type === 'every'">
					<el-form-item label="时间单位">
						<el-radio-group v-model="cronDialog.everyUnit">
							<el-radio :value="'minute'">分钟</el-radio>
							<el-radio :value="'hour'">小时</el-radio>
							<el-radio :value="'day'">天</el-radio>
							<el-radio :value="'week'">周</el-radio>
							<el-radio :value="'month'">月</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="间隔">
						<el-input-number v-model="cronDialog.everyInterval" :min="1" />
					</el-form-item>
				</template>

				<!-- 指定 -->
				<template v-if="cronDialog.type === 'specific'">
					<el-form-item label="时间">
						<el-time-picker v-model="cronDialog.specificTime" format="HH:mm:ss" />
					</el-form-item>
					<el-form-item label="日期">
						<el-radio-group v-model="cronDialog.specificDateType">
							<el-radio :value="'everyday'">每天</el-radio>
							<el-radio :value="'workday'">工作日</el-radio>
							<el-radio :value="'weekend'">周末</el-radio>
							<el-radio :value="'specific'">指定日期</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item v-if="cronDialog.specificDateType === 'specific'">
						<el-date-picker 
							v-model="cronDialog.specificDate"
							type="dates"
							placeholder="选择日期"
						/>
					</el-form-item>
				</template>

				<!-- 周期 -->
				<template v-if="cronDialog.type === 'cycle'">
					<el-form-item label="时间">
						<el-time-picker v-model="cronDialog.cycleTime" format="HH:mm:ss" />
					</el-form-item>
					<el-form-item label="开始日期">
						<el-date-picker 
							v-model="cronDialog.cycleStart"
							type="date"
							placeholder="开始日期"
						/>
					</el-form-item>
					<el-form-item label="结束日期">
						<el-date-picker 
							v-model="cronDialog.cycleEnd"
							type="date"
							placeholder="结束日期"
						/>
					</el-form-item>
				</template>

				<el-form-item>
					<div class="cron-preview">
						生成的表达式: <span class="expression">{{ generatedCron }}</span>
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="cronDialog.visible = false">取 消</el-button>
				<el-button type="primary" @click="applyCron">应 用</el-button>
			</template>
		</el-dialog>
		
	</el-drawer>
</template>

<script lang="ts" setup>
	
	import { ref } from "vue";
	import HttpAPI from "@/api/biz/http";
	import MonacoEditor from '@/components/MonacoEditor/index.vue'
	import EditFieldDrawer from '@/components/DataWorkflow/components/EditFieldDrawer.vue'
	import EditOutputTargetDrawer from '@/components/DataWorkflow/components/EditOutputTargetDrawer.vue'
	import { Plus, Delete, Edit, Rank, Check, Document, Tools } from '@element-plus/icons-vue';
	import draggable from 'vuedraggable';
	import type {FormRules } from 'element-plus'
	import { ElMessage } from "element-plus";
	import { reactive } from "vue";
	import { onMounted } from "vue";
	import { parseJsonToFields } from '@/utils/jsonParser';
	import { validateCronExpression } from '@/utils/validator';
	
	const loading = ref(false);
	const dialog = ref({
		visible:false,
		title:'',
	});
	const editFieldDrawerRef = ref();
	const editOutputTargetDrawerRef = ref();
	const active = ref<number>(0);
	
	
	// 修改 Monaco Editor worker 配置
	// import * as monaco from 'monaco-editor';
	// import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
	// import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
	// import 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution';

	import { ElMessageBox } from "element-plus";
	import { computed } from "vue";
	
	// 配置 Monaco Editor workers
	// window.MonacoEnvironment = {
	// 	getWorker(_moduleId: string, label: string) {
	// 		switch (label) {
	// 			case 'json':
	// 				return new jsonWorker();
	// 			default:
	// 				return new editorWorker();
	// 		}
	// 	}
	// };
	
	const inputFormat=ref<any>();
	
	// 修改编辑器配置
	const monacoInOptions = ref({
		theme: 'vs-dark',
		language: 'sql',
		readOnly: false,
		automaticLayout: true,
		scrollBeyondLastLine: true,
		minimap: { enabled: false },
		lineNumbers: 'on',
		folding: true,
		wordWrap: 'on',
		fontSize: 14,
		tabSize: 2,
		suggestOnTriggerCharacters: true,
		formatOnPaste: true,
		formatOnType: true,
		suggest: {
			preview: true,
			showWords: true,
			showSnippets: true
		},
		contextmenu: true
	});
	
	const fieldDefinitions = ref<any[]>([]);
	const outputDefinitions = ref<any[]>([]);
	const drag = ref(false);
	
	const contentFormRef=ref();
	const contentFormRules=reactive<FormRules>({
		valueFieldType: [{ required: true, message: "请输入取值字段类型.", trigger: "blur" }],
		valueFieldJsonReturnType: [{ required: true, message: "请选择Json内容取值.", trigger: "blur" }],
	});
	
	
	const contentFormData = ref<any>({
	});
	
	const triggerFormRef=ref();
	const triggerFormRules=reactive<FormRules>({
		type: [{ required: true, message: "请选择触发器类型", trigger: "blur" }],
		exec: [{ required: true, message: "请选择执行方式", trigger: "blur" }],
		interval: [{ required: true, message: "请输入间隔时间", trigger: "blur" }],
		unit: [{ required: true, message: "请选择时间单位", trigger: "blur" }],
		expression: [
			{ required: true, message: "请输入CRON表达式", trigger: "blur" },
			{ validator: validateCronExpression, trigger: 'blur' }
		],
		time: [{ required: true, message: "请选择执行时间", trigger: "blur" }],
		dayOfMonth: [{ required: true, message: "请选择日期", trigger: "blur" }],
		month: [{ required: true, message: "请选择月份", trigger: "blur" }],
		timeOfDay: [{ required: true, message: "请选择执行时间", trigger: "blur" }],
	});
	const triggerFormData = ref<any>({
		type: 'timer',
		exec: 'interval'
	});
	
	const completedFormRef=ref();
	const completedFormRules=reactive<FormRules>({
		enabled: [{ required: true, message: "请选择数据任务是否启用.", trigger: "blur" }],
		defaultRunning: [{ required: true, message: "请选择数据任务默认启动.", trigger: "blur" }],
	});
	const completedFormData = ref<any>({
		enabled: '1',
		defaultRunning: '0'
	});
	
	const preStep = () => {
		if(active.value>0){
			active.value-=1
		}
		else{
			active.value=0
		}
	}
	
	const nextStep = () => {
		if(0==active.value){
			contentFormRef.value.validate((isValid: boolean) => {
				if (isValid) {
					active.value=1
				}
			});
		}
		else if(1==active.value){
			if(!fieldDefinitions || fieldDefinitions.value.length<=0){
				ElMessage.warning('请添加清洗与规范内容.');
				return;
			}
			active.value=2
		}
		else if(2==active.value){
			active.value=3
		}
		else if(3==active.value){
			triggerFormRef.value.validate((isValid: boolean) => {
				if (isValid) {
					active.value=4
				}
			});
		}
	}
	
	//输出
	const handleAddOutputTarget = () => {
		editOutputTargetDrawerRef.value.openDialog(-1,null,fieldDefinitions.value,'add');
	};
	
	const handleEditOutputTarget = (index: number,data:any) => {
		editOutputTargetDrawerRef.value.openDialog(index,data,fieldDefinitions.value,'edit');
	};
	
	const removeOutputTarget = (index: number) => {
		ElMessageBox.confirm('确认删除该输出吗？', '提示', {
				type: 'warning'
		}).then(() => {
			outputDefinitions.value?.splice(index, 1);
			ElMessage.success('删除成功');
		});
	};
	
	const handleEditOutputTargetSuccess=(index:number,data:any)=>{
		try {
			if (!outputDefinitions.value) {
				outputDefinitions.value = [];
			}
			if (index > -1) {
				outputDefinitions.value[index] = data;
			} else {
				outputDefinitions.value.push(data);
			}
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	}
	
	//清洗与规范
	const handleAddField = () => {
		editFieldDrawerRef.value.openDialog(-1,null,'add');
	};
	
	const handleEditField = (index: number,data:any) => {
		editFieldDrawerRef.value.openDialog(index,data,'edit');
	};
	
	const removeField = (index: number) => {
		ElMessageBox.confirm('确认删除该字段吗？', '提示', {
				type: 'warning'
		}).then(() => {
			fieldDefinitions.value?.splice(index, 1);
			ElMessage.success('删除成功');
		});
	};
	
	const handleEditFieldSuccess=(index:number,data:any)=>{
		try {
			if (!fieldDefinitions.value) {
				fieldDefinitions.value = [];
			}
			if (index > -1) {
				fieldDefinitions.value[index] = data;
			} else {
				fieldDefinitions.value.push(data);
			}
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	}
	
	const editRow=ref<any>();
	const isEdit=ref<boolean>(false);
	async function openDialog(_row?: any, _type?: string) {
		dialog.value.visible=true;
		dialog.value.title='编辑';
		isEdit.value=true;
		active.value=0;
		editRow.value=_row;
		isEdit.value=true;
		
		const flow=JSON.parse(editRow.value?.flow||"{}");
		
		completedFormData.value.enabled=flow?.enabled;
		completedFormData.value.defaultRunning=flow?.defaultRunning;
		completedFormData.value.remark=flow?.remark;

		if(flow?.content){
			contentFormData.value.valueFieldIdentifier=flow?.content?.valueFieldIdentifier||"";
			contentFormData.value.valueFieldType=flow?.content?.valueFieldType||"";
			contentFormData.value.valueFieldJsonReturnType=flow?.content?.valueFieldJsonReturnType||"";
		}
		if(flow?.standardFields){
			fieldDefinitions.value=flow?.standardFields||[];
		}
		if(flow?.output){
			outputDefinitions.value=flow?.output||[];
		}
		if(flow?.trigger){
			triggerFormData.value.type=flow?.trigger?.type;
			triggerFormData.value.exec=flow?.trigger?.exec;
			triggerFormData.value.interval=flow?.trigger?.interval;
			triggerFormData.value.unit=flow?.trigger?.unit;
			triggerFormData.value.expression=flow?.trigger?.expression;
			triggerFormData.value.time=flow?.trigger?.time;
			triggerFormData.value.dayOfMonth=flow?.trigger?.dayOfMonth;
			triggerFormData.value.month=flow?.trigger?.month;
			triggerFormData.value.timeOfDay=flow?.trigger?.timeOfDay;
		}
	}
	
	/**
	 * 信息保存
	 */
	async function submitForm() {
		if (!completedFormRef.value) return;
		await completedFormRef.value.validate();
		
		loading.value = true;
		try {
			const content: Record<string, any> = {};
			
			content.valueFieldIdentifier = contentFormData.value.valueFieldIdentifier||"";
			content.valueFieldType = contentFormData.value.valueFieldIdentifier||"";
			content.valueFieldJsonReturnType = contentFormData.value.valueFieldJsonReturnType||"";
			
			const trigger: Record<string, any> = {};
			trigger.type = triggerFormData.value.type;
			if (triggerFormData.value.type == 'timer') {
				trigger.exec = triggerFormData.value.exec;
				// 根据不同的执行方式保存相应的属性
				switch (triggerFormData.value.exec) {
					case 'interval':
						trigger.interval = triggerFormData.value.interval;
						trigger.unit = triggerFormData.value.unit;
						break;
						
					case 'cron':
						trigger.expression = triggerFormData.value.expression;
						break;
						
					case 'fixedTime':
						trigger.time = triggerFormData.value.time;
						break;
						
					case 'monthly':
						trigger.dayOfMonth = triggerFormData.value.dayOfMonth;
						trigger.timeOfDay = triggerFormData.value.timeOfDay;
						break;
						
					case 'yearly':
						trigger.month = triggerFormData.value.month;
						trigger.dayOfMonth = triggerFormData.value.dayOfMonth;
						trigger.timeOfDay = triggerFormData.value.timeOfDay;
						break;
				}
			} else if (triggerFormData.value.type == 'event') {
				// 事件触发器的属性
				trigger.eventType = triggerFormData.value.eventType;
				trigger.eventSource = triggerFormData.value.eventSource;
			}
			
			loading.value = true;
			HttpAPI.save({
				id:editRow.value?.id,
				flow:JSON.stringify({
					enabled:completedFormData.value.enabled,
					defaultRunning:completedFormData.value.defaultRunning,
					remark:completedFormData.value.remark,
					content:content,
					standardFields:fieldDefinitions.value,
					output:outputDefinitions.value,
					trigger:trigger,
				})
			})
			.then(() => {
				ElMessage.success("成功");
				active.value=6;
				closeDialog();
			})
			.finally(() => (loading.value = false));
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	}
	
	const emits = defineEmits(['closeDialog'])
	const closeDialog=()=>{
		dialog.value.visible=false;
		dialog.value.title="";
		emits('closeDialog')
		resetForm();
	}
	
	/**
	 * 重置表单
	 */
	function resetForm() {
		isEdit.value=false;
		if(completedFormRef.value){
			completedFormRef.value.resetFields();
			completedFormRef.value.clearValidate();
		}
		
		editRow.value={};
		completedFormData.value.enabled="0";
		completedFormData.value.defaultRunning="0";
		completedFormData.value.remark="";
		
		contentFormData.value={};
		fieldDefinitions.value=[];
		outputDefinitions.value=[];
		triggerFormData.value={};
	}	
	
	defineExpose({
	  openDialog,closeDialog
	});
	
	// JSON解析对话框数据
	const jsonDialog = ref({
		visible: false,
		content: ''
	});
	
	// 处理JSON解析按钮点击
	const handleParseJson = () => {
		jsonDialog.value.visible = true;
		// 如果有valueFieldIdentifier，预填充示例JSON结构
		if (contentFormData.value.valueFieldIdentifier) {
			const structure: any = {};
			const paths = contentFormData.value.valueFieldIdentifier.split('.');
			let current = structure;
			paths.forEach((path: string, index: number) => {
				if (index === paths.length - 1) {
					current[path] = contentFormData.value?.valueFieldType === 'array' ? [{}] : {};
				} else {
					current[path] = {};
					current = current[path];
				}
			});
			jsonDialog.value.content = JSON.stringify(structure, null, 2);
		}
	};
	
	// 解析JSON内容
	const parseJsonContent = () => {
		try {
			const jsonContent = JSON.parse(jsonDialog.value.content);
			let targetJson = jsonContent;

			// 如果设置了取值字段标识，则根据路径获取目标对象
			if (contentFormData.value.valueFieldIdentifier) {
				const paths = contentFormData.value.valueFieldIdentifier.split('.');
				targetJson = paths.reduce((obj: any, path: string) => obj?.[path], jsonContent);

				if (contentFormData.value?.valueFieldType === 'array' && Array.isArray(targetJson)) {
					targetJson = targetJson[0]; // 取数组第一个元素作为结构模板
				}
			}

			if (!targetJson) {
				throw new Error('无法找到指定路径的数据');
			}

			// 解析字段
			const fields = parseJsonToFields(targetJson);
			
			// 添加新字段（避免重复）
			fields.forEach(field => {
				const exists = fieldDefinitions.value.some(
					existingField => existingField.inputFieldIdentifier === field.inputFieldIdentifier
				);
				if (!exists) {
					fieldDefinitions.value.push(field);
				}
			});

			jsonDialog.value.visible = false;
			ElMessage.success('解析成功');
		} catch (error: any) {
			ElMessage.error('JSON解析失败: ' + error.message);
		}
	};
	
	// 常用CRON表达式
	const commonCrons = [
		{ label: '每分钟', value: '0 * * * * ?' },
		{ label: '每小时', value: '0 0 * * * ?' },
		{ label: '每天0点', value: '0 0 0 * * ?' },
		{ label: '每周一0点', value: '0 0 0 ? * MON' },
		{ label: '每月1号0点', value: '0 0 0 1 * ?' },
	];
	
	// 定义类型接口
	interface CronDialogData {
		visible: boolean;
		type: 'every' | 'specific' | 'cycle';
		everyUnit: string;
		everyInterval: number;
		specificTime: any;
		specificDateType: string;
		specificDate: any;
		cycleTime:any;
		cycleStart: any;
		cycleEnd: any;
	}
	
	// CRON生成器对话框数据
	const cronDialog = ref<CronDialogData>({
		visible: false,
		type: 'every',
		everyUnit: 'minute',
		everyInterval: 1,
		specificTime: null,
		specificDateType: 'everyday',
		specificDate: null,
		cycleTime: null,
		cycleStart: null,
		cycleEnd: null
	});
	
	// 生成CRON表达式
	const generatedCron = computed(() => {
		const { type, everyUnit, everyInterval, specificTime, specificDateType, specificDate, cycleTime, cycleStart, cycleEnd } = cronDialog.value;
		
		let expression = '';
		
		switch (type) {
			case 'every':
				switch (everyUnit) {
					case 'minute':
						expression = `0 */${everyInterval} * * * ?`;
						break;
					case 'hour':
						expression = `0 0 */${everyInterval} * * ?`;
						break;
					case 'day':
						expression = `0 0 0 */${everyInterval} * ?`;
						break;
					case 'week':
						expression = `0 0 0 ? * ${everyInterval}`;
						break;
					case 'month':
						expression = `0 0 0 1 */${everyInterval} ?`;
						break;
				}
				break;
				
			case 'specific':
				if (specificTime) {
					const time = new Date(specificTime);
					const seconds = time.getSeconds();
					const minutes = time.getMinutes();
					const hours = time.getHours();
					
					switch (specificDateType) {
						case 'everyday':
							expression = `${seconds} ${minutes} ${hours} * * ?`;
							break;
						case 'workday':
							expression = `${seconds} ${minutes} ${hours} ? * MON-FRI`;
							break;
						case 'weekend':
							expression = `${seconds} ${minutes} ${hours} ? * SAT,SUN`;
							break;
						case 'specific':
							if (specificDate && Array.isArray(specificDate)) {
								const dates = specificDate.map(d => new Date(d).getDate()).join(',');
								expression = `${seconds} ${minutes} ${hours} ${dates} * ?`;
							}
							break;
					}
				}
				break;
				
			case 'cycle':
				if (cycleTime && cycleStart && cycleEnd) {
					const time = new Date(cycleTime);
					const seconds = time.getSeconds();
					const minutes = time.getMinutes();
					const hours = time.getHours();
					
					const start = new Date(cycleStart);
					const end = new Date(cycleEnd);
					const startDay = start.getDate();
					const endDay = end.getDate();
					
					expression = `${seconds} ${minutes} ${hours} ${startDay}-${endDay} * ?`;
				}
				break;
		}
		
		return expression;
	});
	
	// 打开CRON生成器
	const openCronBuilder = () => {
		cronDialog.value.visible = true;
	};
	
	// 应用生成的CRON表达式
	const applyCron = () => {
		if (generatedCron.value) {
			triggerFormData.value.expression = generatedCron.value;
			cronDialog.value.visible = false;
		}
	};
	
	onMounted(() => {
	});

</script>

<style scoped>
	.step-content{
		background-color: aliceblue;
		margin-top: 8px;
		padding: 8px;
		padding-top: 16px;
	}
	
	.title-form_primary {
	    font-style: normal;
	    font-weight: 500;
	    font-size: 14px;
	    color: #1f2329;
	    position: relative;
	    padding-left: 5px;
	}
	.title-form_primary:before {
	  content: "";
	  width: 2px;
	  height: 14px;
	  background: var(--el-color-primary);
	  position: absolute;
	  top: 50%;
	  transform: translateY(-50%);
	  left: 0;
	}
	
	
	.section-title {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  margin-bottom: 16px;
	}
	
	
	.param-model-content {
	  padding: 16px;
	  background: var(--el-fill-color-light);
	  border-radius: 4px;
	}
	
	.param-model-content-row {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  padding: 12px 8px;
	  margin-bottom: 8px;
	  background: var(--el-bg-color);
	  border: 1px solid var(--el-border-color-lighter);
	  border-radius: 4px;
	  transition: all 0.3s;
	  
	  &:hover {
	    border-color: var(--el-border-color);
	    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	  }
	}
	
	.param-info {
	  flex: 1;
	}
	
	.param-name {
	  border-radius: 4px;
	  font-weight: 500;
	  color: var(--el-text-color-secondary);
	}
	
	.param-detail {
	  display: flex;
	  align-items: center;
	  gap: 16px;
	  color: var(--el-text-color-secondary);
	  font-size: 13px;
	}
	
	.param-actions {
	  display: flex;
	  gap: 8px;
	}
	
	.empty-tip {
	  text-align: center;
	  color: var(--el-text-color-secondary);
	  padding: 32px 0;
	}
	
	.drag-handle {
	  cursor: move;
	  margin-right: 8px;
	  color: var(--el-text-color-secondary);
	  
	  &:hover {
	    color: var(--el-text-color-primary);
	  }
	}
	
	.flip-list-move {
	  transition: transform 0.5s;
	}
	
	.no-move {
	  transition: transform 0s;
	}
	
	.ghost {
	  opacity: 0.5;
	  background: #c8ebfb;
	}
	
	.sql-editor-container {
		margin-bottom: 16px;
		border: 1px solid var(--el-border-color-light);
		border-radius: 4px;
		overflow: hidden;
	
		.sql-editor {
			height: 200px;
			border-radius: 4px;
		}
	
		.sql-tips {
			padding: 8px;
			background-color: var(--el-bg-color-page);
			border-top: 1px solid var(--el-border-color-light);
		}
	}
	
	.cron-tips {
	  margin-top: 8px;
	  font-size: 12px;
	  color: var(--el-text-color-secondary);
	  
	  p {
	    margin: 4px 0;
	  }
	}
	
	.cron-tag {
	  margin-right: 8px;
	  margin-bottom: 8px;
	  cursor: pointer;
	  
	  &:hover {
	    opacity: 0.8;
	  }
	}
	
	.cron-preview {
	  margin-top: 16px;
	  padding: 12px;
	  background: var(--el-fill-color-light);
	  border-radius: 4px;
	  
	  .expression {
	    color: var(--el-color-primary);
	    font-weight: bold;
	    margin-left: 8px;
	  }
	}
</style>